<!-- 登录和注册 -->
<script setup>
import { User, Lock, Check } from '@element-plus/icons-vue'
import { ref, onMounted, reactive } from 'vue'
import { ElNotification } from 'element-plus'
import { useRouter } from 'vue-router'
import { LoginAPI } from '@/api/login'
// import { useUserStore } from '@/stores'
const router = useRouter()
const isRegister = ref(false)
//实现验证码倒计时操作
const show = ref(true)
const count = ref('')
const timer = ref(null)
const getCode = () => {
  const TIME_COUNT = 60
  if (!timer.value) {
    count.value = TIME_COUNT
    show.value = false
    timer.value = setInterval(() => {
      if (count.value > 0 && count.value <= TIME_COUNT) {
        count.value--
      } else {
        show.value = true
        clearInterval(timer.value)
        timer.value = null
      }
    }, 1000)
  }
}

// //注册功能
// const ChangeRegister = () => {
//   //validate  整体进行效验，点击注册重新对整体进行效验
//   ElMessage.success('注册成功')
//   //切换到登录页面
//   isRegister.value = false
// }
const form = ref(null)
//注册功能 ---- 整个用于提交的form数据对象
//把用户输入的进行同步,并进行验证,传数据
//提供数据
const formModel = reactive({
  username: '',
  password: '',
  repassword: '',
  remember: false,
  captcha: ''
})
//整个表单的效验规则
const rules = {
  username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  password: [
    { required: true, message: '用户密码不能为空', trigger: 'blur' },
    { pattern: /^\S{5,15}$/, message: '密码是6-15位非空字符', trigger: 'blur' }
  ]
}

//登录业务实现
const login = () => {
  form.value.validate((valid) => {
    // 通过校验
    if (valid) {
      //验证成功，发送登录请求
      console.log('验证通过')

      LoginAPI(formModel).then((res) => {
        console.log(res)

        if (res.data.code == 2) {
          //存储令牌
          sessionStorage.token = res.data.token
          console.log(res.data)
          //路由跳转
          router.push('/home')
        } else if (res.data.code == 1) {
          //存储令牌
          sessionStorage.token = res.data.token

          console.log(res.data.massage)
          localStorage.setItem('userName', res.data.user.name)
          localStorage.setItem('teacherId', res.data.user.teacherId)
          localStorage.setItem('userInfo', JSON.stringify(res.data.user))
          // console.log('老师名称：' + res.data.user.name)
          // console.log('老师ID：' + res.data.user.teacherId)
          //路由跳转
          router.push('/teacher')
        } else {
          ElNotification({
            title: '错误',
            message: res.data.massage,
            type: 'error'
          })
        }
      })
    }
  })
}

//注册业务逻辑
const register = () => {
  router.push('/reg')
}

// //数据回显
// //数据回显
const showUserInfo = () => {
  const userStr = localStorage.getItem('info')
  if (userStr) {
    const userObj = JSON.parse(userStr)
    formModel.username = userObj.stuId
  }
}
onMounted(() => {
  showUserInfo() // 生命周期函数的使用
})
</script>

<template>
  <el-row class="login-page">
    <el-col :span="20" class="form" style="margin-left: 1.25rem; margin-top: 2.5rem">
      <!--  autocomplete="off"---input表单输入框不记录输入过信息的方法--->
      <el-form
        :model="formModel"
        :rules="rules"
        size="large"
        ref="form"
        autocomplete="off"
        v-if="isRegister"
      >
      </el-form>

      <!-- 登录相关表单 -->
      <el-form :model="formModel" :rules="rules" size="large" ref="form" autocomplete="off" v-else>
        <el-form-item prop="stuId">
          <el-input
            v-model="formModel.username"
            :prefix-icon="User"
            style="height: 2.5rem"
            clearable="true"
            placeholder="请输入学号/职工号"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="formModel.password"
            name="password"
            :prefix-icon="Lock"
            type="password"
            show-password="true"
            clearable="true"
            style="height: 2.5rem"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item class="flex"> </el-form-item>
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="login()"
            >登录</el-button
          >
          <div class="flex">
            <el-link :underline="false">忘记密码?</el-link>
            <el-link :underline="false" @click="register">免费注册</el-link>
            <el-link :underline="false" @click="isRegister = true">动态登录</el-link>
          </div>
        </el-form-item>
      </el-form>
      <el-form
        :model="formModel"
        :rules="rules"
        size="large"
        ref="form"
        autocomplete="off"
        v-if="isRegister"
      >
        <el-form-item prop="username">
          <el-input
            v-model="formModel.username"
            :prefix-icon="User"
            clearable="true"
            placeholder="请输入手机号码"
          ></el-input>
        </el-form-item>
        <!-- 给手机端发送验证码进行注册 -->
        <el-form-item prop="captcha">
          <el-row :gutter="20">
            <el-col :span="17">
              <el-input
                :prefix-icon="Check"
                v-model="formModel.captcha"
                placeholder="验证码"
                clearable
              />
            </el-col>
            <el-col :span="7">
              <el-button type="primary" class="button" @click="getCode" v-show="show"
                >获取验证码</el-button
              >
              <el-button class="btn-get" v-show="!show">{{ count }}(s)后重新获取</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space> 登录 </el-button>
        </el-form-item>
        <!---将该元素放在末尾-->
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = false"> ← 返回 </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
.login-page {
  height: 12.5rem;
  background-color: #fff;
  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    .button {
      width: 100%;
      margin-bottom: 0.625rem;
      background: #7cd4c6;
      border: #7cd4c6;
    }
    .btn-get {
      width: 6.25rem;
      margin-bottom: 0.625rem;
      margin-right: 6.25rem;
    }
    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
      margin-top: 1.25rem;
    }
  }
}
</style>
